package fivestar.model.dao.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import fivestar.model.dao.UserDao;
import fivestar.model.entity.User;
import fivestar.util.HibernateUtil;

public class UserDaoHibernate implements UserDao{

	Session session = null;
    Transaction tx = null;
    
	@Override
	public User login(String name, String password) throws RuntimeException {
		 User user= null;
		 session = HibernateUtil.getSessionFactory().openSession();
	        try { 
	        	
	        	tx = session.beginTransaction();

	            Query query = session.createQuery("from User as u Where u.name= :name and u.password =:password");
	            query.setParameter("name", name);
	            query.setParameter("password", password);

	            user = (User) query.uniqueResult();
	            
	        } catch (HibernateException e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.flush();
	            session.close();
	        }
	        
	        return user;
	}

}
